<template>
  <component
    :is="h(ElMenu, { ...$attrs, ...props, defaultActive }, $slots)"
    @select="onSelect"
  >
    <NavigationMenuItem :items="menuItem" />
  </component>
</template>
<script lang="ts" setup>
import { h, onMounted } from "vue";
import NavigationMenuItem from "./NavigationMenuItem.vue";
import type { MenuItem, MenuMapping, SelectItem } from "./types";
import { getMenuMapping } from "./types";
import { ElMenu } from "element-plus";
import { menuProps } from "element-plus";
import { useRoute } from "vue-router";
import { ref } from "vue";

const route = useRoute();

const props = defineProps({
  ...menuProps,
  menuItem: { type: Array as () => MenuItem[], default: () => [] },
});

const defaultActive = ref(props.defaultActive);

const routrNameToMenuID = ref<MenuMapping>({});
const menuIDToRouteName = ref<MenuMapping>({});
onMounted(() => {
  // 菜单ID映射路由名称
  menuIDToRouteName.value = getMenuMapping(props.menuItem, "id", "routeName");
  routrNameToMenuID.value = getMenuMapping(props.menuItem, "routeName", "id");
  // 根据路由名称获取菜单ID
  defaultActive.value = routrNameToMenuID.value[route.name as string].id || "";
});

const emits = defineEmits<{
  (e: "select", items: SelectItem): void;
}>();

const onSelect = (index: string) => {
  emits("select", menuIDToRouteName.value[index] as SelectItem);
};
</script>

<style scoped lang="less">
.el-menu--vertical {
  border-right: 0;
}
</style>
